<script setup>
import imgLoginBg from '@/assets/images/login-bg.jpg'
import { PHONE_REG } from '@/utils'
import { userApi, smsApi } from '@/api'
import { useCountdown } from '@/hooks'

const router = useRouter()

const ruleForm = ref({
  code: '',
  userPhone: ''
})
const rules = {
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'change'
    },
    {
      pattern: /^[\d]+$/,
      message: '请输入数字验证码',
      trigger: 'blur'
    }
  ],
  userPhone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: 'change'
    },
    {
      pattern: PHONE_REG,
      message: '请输入正确的手机号',
      trigger: 'blur'
    }
  ]
}
const ruleFormRef = ref()
async function handleSubmit() {
  await ruleFormRef.value.validate()

  await userApi.retrievePassword(ruleForm.value)

  ElMessage.success('找回成功，请查看手机短信')
  router.push('/login')
}

async function sendCode() {
  await ruleFormRef.value.validateField('userPhone')

  await smsApi.getCaptcha({
    smsPhone: ruleForm.value.userPhone,
    applicationType: 5 // 应用类型；1：登录验证；2：导入验证；3：删除验证；4:注册验证 5-修改、找回密码
  })

  ElMessage.success('发送成功，请查看手机短信')
  start()
}

const { count, isRunning, start } = useCountdown(60)
</script>

<template>
  <div
    class="flex min-h-screen flex-col items-center"
    :style="{ background: `url(${imgLoginBg}) left top / cover no-repeat` }"
  >
    <div class="mx-auto my-auto w-full max-w-lg justify-self-center p-4 sm:p-0">
      <p class="-mt-16 mb-6 text-center">找回密码</p>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-position="top"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="手机号" prop="userPhone">
          <el-input v-model="ruleForm.userPhone">
            <template #suffix>
              <el-button
                link
                type="primary"
                :disabled="isRunning"
                @click="sendCode"
              >
                {{ isRunning ? `${count}秒后重新获取` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code" />
        </el-form-item>
        <el-form-item>
          <div class="flex w-full items-center">
            <el-button class="flex-1" @click="router.back()"> 返回 </el-button>
            <el-button
              type="primary"
              class="flex-1"
              native-type="submit"
              @submit="handleSubmit"
            >
              立即找回
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
